package com.vision.bigDataApi.config;

import com.vision.bigDataApi.model.dto.Result;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ResultPool {
	@Value("${result.pool.minIdle}")
	private int minIdle;
	@Value("${result.pool.maxTotal}")
	private int maxTotal;
	@Value("${result.pool.maxWaitMillis}")
	private long maxWaitMillis;
	private static class SimpleResultPool extends GenericObjectPool<Result> {

		public SimpleResultPool(PooledObjectFactory<Result> factory, GenericObjectPoolConfig config) {
			super(factory, config);
		}
		
	}
	
	private static class ResultFactory extends BasePooledObjectFactory<Result>{

		@Override
		public Result create() throws Exception {
			return new Result();
		}

		@Override
		public PooledObject<Result> wrap(Result result) {
			return new DefaultPooledObject<Result>(result);
		}
	}
	
	public static class ResultPoolWrap{
		private GenericObjectPool<Result> pool;

		public GenericObjectPool<Result> getPool() {
			return pool;
		}

		public void setPool(GenericObjectPool<Result> pool) {
			this.pool = pool;
		}
	}
	/**
	 * 进行了包装，如果直接把SimpleResultPool交给容器进行创建和管理，会和MBean里的GenericObjectPool冲突
	 * @return
	 */
	@Bean
	public ResultPoolWrap getSimpleResultPool(){
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setMinIdle(minIdle);
		config.setMaxTotal(maxTotal);
		config.setMaxWaitMillis(maxWaitMillis);
		ResultPoolWrap wrap = new ResultPoolWrap();
		wrap.setPool(new SimpleResultPool(new ResultFactory(), config));
		return wrap;
	}
	
	
}
